<template>
  <div>
    <!--<el-tooltip class="item" effect="dark" content="锁屏" placement="top-start">
      <i class="btn iconfont icon-suoping" @click="clickLock()"></i>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="主题" placement="top-start">
      <i class="btn iconfont icon-zhuti" @click="clickhexagon()"></i>
    </el-tooltip>-->
    <el-tooltip class="item" effect="dark" content="磁盘将满告警" placement="top-start">
      <i v-show="this.alarming" style="color: orange" class="btn iconfont icon-xiaoxi" @click="diskAlarmMessage()">
      </i>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="磁盘已满告警" placement="top-start">
      <i v-show="this.fullAlarmed" style="color: red" class="btn iconfont icon-xiaoxi" @click="diskAlarmMessage()">
      </i>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="当前时间" placement="top-start">
      <span style="min-width: 40px; color:white;">{{ timeInfo }}</span>
    </el-tooltip>
    <div class="btn user-op">
      <i class="iconfont icon-user"></i>
      <span style="min-width: 40px;">{{ username }}</span>
      <i class="iconfont icon-xia"></i>
      <ul>
        <li @click="edition">
          <i class="el-icon-setting"></i>关于系统
        </li>
        <!-- <li><i class="iconfont icon-alert-circle"></i>个人信息</li>-->
        <li @click="openDialog">
          <i class="el-icon-key"></i>修改密码
        </li>
        <li @click="logout">
          <i class="el-icon-switch-button"></i>退出登录
        </li>
      </ul>
    </div>
    <el-dialog
        :title="title"
        :visible.sync="showModifyPasswordDialog"
        append-to-body="true"
        width="600px"
        :close-on-click-modal="false"
        @close="closePasswordForm"
    >
      <el-container>
        <el-main>
          <el-form ref="passwordForm" :model="passwordForm" label-width="80px" :rules="rules">
            <el-form-item label="原密码" ref="oldPassword" prop="oldPassword">
              <el-input
                  type="text"
                  placeholder="请输入原密码"
                  v-model="passwordForm.oldPassword"
                  @blur="onInputBlur" @input="oldPassInput"
              />
            </el-form-item>
            <el-form-item label="新密码" ref="newPassword" prop="newPassword">
              <el-input type="text" v-model="passwordForm.newPassword" placeholder="请输入新密码" :maxlength="maxPwdLength"
                        @input="newPass1Input"/>
            </el-form-item>
            <el-form-item label="确认密码" ref="confirmPassword" prop="confirmPassword">
              <el-input type="text" v-model="passwordForm.confirmPassword" placeholder="请确认密码" :maxlength="maxPwdLength"
                        @input="newPass2Input"/>
            </el-form-item>
          </el-form>
        </el-main>
      </el-container>
      <div slot="footer" class="dialog-footer">
        <el-button @click="savePasswordForm" type="primary">确 定</el-button>
        <el-button @click="closePasswordForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import partMsgs from "./Msgs";
// import partLock from "./Lock";
// import partPwd from "./Pwd";
import LoginSrv from "../../api/login.service";
import aesUtils from "@/core/utils/aes.utils";
import { log } from 'util';

export default {
  components: {
    // partMsgs,
    // partLock,
    // partPwd
  },
  data() {
    var validateIdNumber = (rule, value, callback) => {
      console.log(value.length);
      if (this.newPassword1 !== "") {
        if (this.newPassword1.length >= this.minPwdLength && this.newPassword1.length <= this.maxPwdLength) {
          // 数字和字母组合的正则
          var reg = /^(?=.*\d)(?=.*[a-zA-Z])[\da-zA-Z]{8,}$/;
          //  数字和字母和特殊符合组合 正则
          var reg1 = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*?])[\da-zA-Z~!@#$%^&*?]{8,}$/;
          if (reg.test(this.newPassword1) === true || reg1.test(this.newPassword1) === true) {
            callback();
          } else {
            callback(
              new Error(
                `口令长度${this.minPwdLength}到${this.maxPwdLength}位，且至少为数字和字母的组合，仅支持特殊字符：~!@#$%^&*?`
              )
            );
          }
        } else {
          callback(
            new Error(
              `口令长度${this.minPwdLength}到${this.maxPwdLength}位，且至少为数字和字母的组合，仅支持特殊字符：~!@#$%^&*?`
            )
          );
        }
      } else {
        callback();
      }
    };
    var validatePass1 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value == this.passwordForm.oldPassword) {
        callback(new Error("新密码不能和原密码相同!"));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (this.newPassword2 === "") {
        callback(new Error("请再次输入密码"));
      } else if (this.newPassword1 !== this.newPassword2) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      // username: this.$store.state.core.user.username,
      fullAlarmed: false,
      alarming: false,
      diskAlarmMsg: "",
      username: sessionStorage.getItem("username"),
      title: "修改密码",
      showModifyPasswordDialog: false,
      passwordForm: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },
      oldPassword: "",
      newPassword1: "",
      newPassword2: "",
      timer: null,
      rules: {
        oldPassword: [{required: true, message: "原密码不能为空！"}],
        newPassword: [
          {required: true, message: "新密码不能为空！"},
          // {
          //   pattern: /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$)^.{6,10}$/,
          //   message: "密码必须含有大小写字母和数字6 到 10 个字符！",
          //   trigger: "blur",
          // },
          {
            validator: validateIdNumber,
            trigger: "blur",
          },
          // { validator: validatePass1, trigger: "blur" },
        ],
        confirmPassword: [
          {required: true, message: "确认密码不能为空！"},
          {validator: validatePass2, trigger: "blur"},
        ],
      },
      minPwdLength: 0,
      maxPwdLength: 0,
      getTimer: null,
      timeInfo: '',
      nowTime: new Date(),
      getSecondsTimer: null,
    };
  },
  watch:{
    "$route":{
      handler(n){
        if(n && n.name == 'home'){
              this.initPwdLength();
              this.diskCheck();
              this.initPwd();
        }
      },
      immediate:true,
      deep:true
    }
  },
  created() {
    // this.initPwdLength();
    // this.diskCheck();
    // this.initPwd();
  },
  mounted() {
    this.timer = setInterval(() => {
      // 模拟手动点击
      LoginSrv.checkTokenEx().then(res => {
        if (res.data.code !== 10200) {
          clearInterval(this.timer);
          clearInterval(this.getTimer);
          clearInterval(this.getSecondsTimer);
          sessionStorage.clear();
          this.$message.error(res.data.msg);
          this.$router.push("/login");
        }
        this.nowTime = res.headers.date;
        this.changeTime();

      })
    }, 1000 * 12);
    // 更新时间
    this.getSecondsTimer = setInterval(()=>{
      this.changeTime();
    },1000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
    clearInterval(this.getTimer);
    clearInterval(this.getSecondsTimer);
  },
  methods: {
    // 更新时间
    changeTime() {
      let that = this;
      if (that.nowTime) {
        let t = new Date(that.nowTime).getTime();
        t += 1000;
        let time = new Date(t);
        that.nowTime = new Date(t);
        let month = time.getMonth() + 1;
        if (month < 10) {
          month = "0" + month;
        }
        let date = time.getDate();
        if (date < 10) {
          date = "0" + date;
        }
        let hours = time.getHours();
        if (hours < 10) {
          hours = "0" + hours;
        }
        let minutes = time.getMinutes();
        if (minutes < 10) {
          minutes = "0" + minutes;
        }
        let seconds = time.getSeconds();
        if (seconds < 10) {
          seconds = "0" + seconds;
        }
        this.timeInfo = time.getFullYear() + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
      }
    },
    initPwdLength() {
      LoginSrv.getSafePolicy().then((res) => {
        if (res.code !== 10200) return this.$message.error(res.msg);
        this.minPwdLength = Number(res.data.sysPassShortLength);
        this.maxPwdLength = Number(res.data.sysPassLength);
      });
    },
    initPwd() {
        let msg = "密码已经过期请修改密码，谢谢！";
        let res = JSON.parse(window.sessionStorage.getItem('allUserInfo'))
        if (res.isFirstLogin) {
          msg = "第一次登录，请修改密码！"
        }
        if (res.isTipPassUpdate || res.isFirstLogin) {
          this.$confirm(msg, "提示", {
            confirmButtonText: "确定",
            type: "warning",
            center: true,
          })
            .then(() => {
              this.openDialog()
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消！",
              });
            });
        }


      // LoginSrv.getInfo().then((res) => {
      //   if (res.code !== 10200) this.$message.error(res.msg);
      //   sessionStorage.setItem("roleCodes", res.data.roleCodes)
      //   let msg = "密码已经过期请修改密码，谢谢！";
      //   if (res.data.isFirstLogin) {
      //     msg = "第一次登录，请修改密码！"
      //   }
      //   if (res.data.isTipPassUpdate || res.data.isFirstLogin) {
      //     this.$confirm(msg, "提示", {
      //       confirmButtonText: "确定",
      //       type: "warning",
      //       center: true,
      //     })
      //       .then(() => {
      //         this.openDialog()
      //       })
      //       .catch(() => {
      //         this.$message({
      //           type: "info",
      //           message: "已取消！",
      //         });
      //       });
      //   }
      // });
    },
    oldPassInput() {
      let hh = "";
      let pass = "";
      for (let i = 0; i < this.passwordForm.oldPassword.length; i++) {
        hh += "*";
        if (this.passwordForm.oldPassword.charAt(i) != "*") {
          pass += this.passwordForm.oldPassword.charAt(i);
        } else {
          pass += this.oldPassword.charAt(i);
        }
      }
      this.oldPassword = pass;
      this.passwordForm.oldPassword = hh;

    },
    newPass1Input() {
      let hh = "";
      let pass = "";
      for (let i = 0; i < this.passwordForm.newPassword.length; i++) {
        hh += "*";
        if (this.passwordForm.newPassword.charAt(i) != "*") {
          pass += this.passwordForm.newPassword.charAt(i);
        } else {
          pass += this.newPassword1.charAt(i);
        }
      }
      this.newPassword1 = pass;
      this.passwordForm.newPassword = hh;

    },
    newPass2Input() {
      let hh = "";
      let pass = "";
      for (let i = 0; i < this.passwordForm.confirmPassword.length; i++) {
        hh += "*";
        if (this.passwordForm.confirmPassword.charAt(i) != "*") {
          pass += this.passwordForm.confirmPassword.charAt(i);
        } else {
          pass += this.newPassword2.charAt(i);
        }
      }
      this.newPassword2 = pass;
      this.passwordForm.confirmPassword = hh;

    },
    // 关于
    edition() {
      // this.$confirm(`版本号${PUZZLE_CONFIG.ceshiVersion}`, "提示", {
      //   cancelButtonText: "取消",
      //   type: "warning"
      // })
      this.$alert(`版本号${PUZZLE_CONFIG.ceshiVersion}`, "系统版本", {
        confirmButtonText: "确定",
        callback: (action) => {
        },
      });
    },
    // 失去焦点
    onInputBlur() {
    },
    clearData() {
      this.$router.push({path: "/login"});
      // sessionStorage.removeItem("token");
      // sessionStorage.removeItem("refresh_token");
      // sessionStorage.removeItem("username");
      // sessionStorage.removeItem("userId");
      // sessionStorage.removeItem("permissions");
      // sessionStorage.removeItem("isTipPassUpdate");
      // sessionStorage.removeItem("TENANT-ID");
      // sessionStorage.removeItem("tabList");
      // sessionStorage.removeItem("allUserInfo");
      sessionStorage.clear()
    },
    logout() {
      this.$confirm("此操作退出登录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let username = sessionStorage.getItem("username");
          let roleCodes = sessionStorage.getItem("roleCodes");
          LoginSrv.logout(username,roleCodes)
            .then((item) => {
              if (item.code == 10200) {
                this.clearData();
                this.$store.commit("SET_TAB", []);
                this.$message({
                  type: "success",
                  message: "退出登录成功",
                });
              }
            })
            .catch((error) => {
              this.clearData();
              this.$router.push("/login");
              this.$store.commit("CLEAR_TAB");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消退出",
          });
        });
    },
    // editUser
    savePasswordForm() {
      this.$refs["passwordForm"].validate((valid) => {
        if (valid) {
          let obj = {
            id: sessionStorage.getItem("userId"),
            username: sessionStorage.getItem("username"),
            password: aesUtils.encode(this.oldPassword),
            newpassword: aesUtils.encode(this.newPassword1),
            newpassword1: aesUtils.encode(this.newPassword2),
          };
          LoginSrv.editUser(obj).then((res) => {
            if (res.code == 10200) {
              this.clearData();
              this.$message({
                type: "success",
                message: "密码修改成功，请重新登录！",
              });
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          return false;
        }
      });
    },

    closePasswordForm() {
      let obj = {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      };
      this.passwordForm = obj;
      this.$refs["passwordForm"].resetFields();
      this.showModifyPasswordDialog = false;
    },
    openDialog() {
      this.showModifyPasswordDialog = true;
    },
    // 锁屏
    clickLock() {
      this.$message({
        showClose: true,
        message: "功能优化中，敬请期待哦！",
        type: "warning",
      });
    },
    // 消息
    clickbell() {
      this.$message({
        showClose: true,
        message: "功能优化中，敬请期待哦！",
        type: "warning",
      });
    },
    // 主题
    clickhexagon() {
      this.$message({
        showClose: true,
        message: "功能优化中，敬请期待哦！",
        type: "warning",
      });
    },
    // 磁盘告警
    diskCheck() {
      // if(sessionStorage)
      LoginSrv.diskCheck().then((res) => {
        if (res.code == 10200) {
          //已满告警
          if (res.data.fullAlarmed) {
            this.fullAlarmed = res.data.fullAlarmed
            this.diskAlarmMessage()
          }
          //将满告警
          if (res.data.alarming) {
            this.alarming = res.data.alarming
            this.diskAlarmMessage()
          }
        } else {
          this.fullAlarmed = false
          this.alarming = false
        }
      })
    },
    //磁盘告警消息提示
    diskAlarmMessage() {
      if (this.fullAlarmed) {
        this.diskAlarmMsg = "磁盘空间已满，请处理！"
      }
      if (this.alarming) {
        this.diskAlarmMsg = "磁盘空间将满，请处理！"
      }
      this.$confirm(this.diskAlarmMsg, "提示", {
        confirmButtonText: "确定",
        type: "warning",
        center: true,
      })
        .then(() => {
          // TODO 处理
          this.$router.push("/tpf/upms/views/diskCheck/diskCheckIndex");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消！",
          });
        });

    }
  },
};
</script>

<style lang="less">
  @import "~@frames/dashboard/style/var";

  #topbarBtns {
    height: @topBarH;
    padding-right: 15px;

    .btn {
      display: inline-block;
      padding: 0 12px;
      font-size: 18px;
      line-height: @topBarH;
      color: #fff;
      cursor: pointer;

      transition: all 0.2s;

      &:hover {
        background: rgba(255, 255, 255, 0.1);
      }
    }

    .user-op {
      position: relative;
      margin-left: 19px;
      cursor: default;

      &:hover {
        ul {
          visibility: visible;
          opacity: 1;
          transform: translateY(0);
        }
      }

      &:after {
        position: absolute;
        content: "";
        left: -10px;
        background: rgba(0, 0, 0, 0.07);
        top: 10px;
        bottom: 10px;
        width: 1px;
      }

      .icon-user {
        display: inline-block;
        vertical-align: top;
        font-size: 21px;
        line-height: @topBarH;
        color: #fff;
      }

      span {
        display: inline-block;
        padding: 0 6px;
        font-size: 14px;
        vertical-align: top;
      }

      .icon-chevron-down {
        vertical-align: middle;
        margin-top: -5px;
        font-size: 12px;
        font-weight: bold;
      }

      ul {
        position: absolute;
        top: @topBarH;
        right: 0;
        left: 0;
        background: #fff;
        box-shadow: 0px 2px 5px 0px rgba(0, 0, 0, 0.05);
        color: #444;
        padding: 8px 0;
        border-radius: 0 0 3px 3px;

        transition: all 0.2s;
        visibility: hidden;
        opacity: 0;
        transform: translateY(10px);

        li {
          text-align: center;
          font-size: 13px;
          font-weight: bold;
          line-height: 34px;

          i {
            margin-right: 6px;
            font-size: 13px;
          }

          &:hover {
            background: @hover;
          }
        }
      }
    }
  }
</style>
